package com.jimet.security;


import javax.crypto.*;
import javax.crypto.spec.*;

public class AES {

  /**
  * Turns array of bytes into string
  *
  * @param buf	Array of bytes to convert to hex string
  * @return	Generated hex string
  */
  public static String asHex (byte buf[]) {
   StringBuffer strbuf = new StringBuffer(buf.length * 2);
   int i;

   for (i = 0; i < buf.length; i++) {
    if (((int) buf[i] & 0xff) < 0x10)
	    strbuf.append("0");
    strbuf.append(Long.toString((int) buf[i] & 0xff, 16));
   }

   return strbuf.toString();
  }

  /**	generates a new random AES SecretKey for 
   * use in future encryption/decryptions
 * @return The secretkey object generated.
 * @throws Exception
 */
public static SecretKey generateSecretKey() throws Exception
  {
	    // Get the KeyGenerator
	    KeyGenerator kgen = KeyGenerator.getInstance("AES");
	    kgen.init(128); // 192 and 256 bits may not be available

		// Generate the secret key specs.
	    SecretKey sKey = kgen.generateKey();

		return sKey;
  }
  
  /** Encrypts the given String into a byte array using the secret key supplied.
 * @param message String to encrypt
 * @param sKey secretKey object, possibly generated 
 * by generateKey() method of this class.
 * @return byte array holding the encrypted value.
 * @throws Exception
 */
public static byte [] encrypt(String message, SecretKey sKey) throws Exception {

    byte[] raw = sKey.getEncoded();
    SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");

    // Instantiate the cipher
    Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.ENCRYPT_MODE, skeySpec);

    byte[] encrypted =
      cipher.doFinal(message.getBytes());
//    return asHex(encrypted);
	
	return encrypted;
//	String hexString = HexConverter.byteArrayToHexString(encrypted);
//    return hexString;

  }

  /** Decrypt the given byte array into original byte array using the secret key supplied
 * @param encrypted - pre-encrypted byte[]
 * @param sKey - SecretKey Object
 * @return - Original byte array
 * @throws Exception
 */
public static byte[] decrypt(byte [] encrypted, SecretKey sKey) throws Exception
  {
	  
	    byte[] raw = sKey.getEncoded();
	    SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");

	    // Instantiate the cipher
	    Cipher cipher = Cipher.getInstance("AES");

		cipher.init(Cipher.DECRYPT_MODE, skeySpec);
	    cipher.doFinal(encrypted);
		
		return encrypted;

  }


}

